<template>
	<el-dialog :visible.sync="visible" title="升级DCU" :close-on-click-modal="false" @close="close"
		:close-on-press-escape="false">
		<el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmitHandle()"
			label-width="120px">
			<el-form-item prop="dcu" label="门控单元编号">
				<el-select v-model="dataForm.dcu" multiple collapse-tags filterable clearable @change="getdoorChange">
					<el-checkbox v-model="checkOptions.checkAll" :style="{ paddingLeft: '20px' }"
						:indeterminate="checkOptions.isIndeterminate" @change="handleCheckAllChange">
						全选
					</el-checkbox>
					<el-checkbox v-model="checkOptions.checkUp" :style="{ paddingLeft: '20px' }"
						:indeterminate="checkOptions.isIndeterminateup" @change="handleCheckUpChange">
						上行
					</el-checkbox>
					<el-checkbox v-model="checkOptions.checkDown" :style="{ paddingLeft: '20px' }"
						:indeterminate="checkOptions.isIndeterminatedown" @change="handleCheckDownChange">
						下行
					</el-checkbox>
					<el-option v-for="(item, index) in options2" :key="index" :label="item.dcu" :value="item.dcu">
					</el-option>
				</el-select>
			</el-form-item>
		</el-form>
		<template slot="footer">
			<el-button @click="visible = false">{{ $t("cancel") }}</el-button>
			<el-button type="primary" @click="dataFormSubmitHandle()">{{
        $t("confirm")
      }}</el-button>
		</template>
		<div v-if="loading" class="loadingContent el-loading-mask">
			<div @click="closeLoading" class="loadingClose"></div>
			<div class="el-loading-spinner">
				<svg viewBox="25 25 50 50" class="circular">
					<circle cx="50" cy="50" r="20" fill="none" class="path"></circle>
				</svg>
				<p class="el-loading-text" style="font-size: 20px;">{{ loadingMsg }}</p>
			</div>
		</div>
	</el-dialog>
</template>
<script>
	import debounce from "lodash/debounce";
	import utils from "@/utils/utils";
	import axios from 'axios'
	import Cookies from "js-cookie";
	import { getOrder,getStep} from "@/utils";
	export default {
		props: ["jdNumber"],
		data() {
			return {
				visible: false,
				dataForm: {
					cpuId: "",
					dcu: [],
					packagePath: "",
				},
				options: utils.cpuType,
				options2: [],
				optionsup: [],
				optionsdown: [],
				checkOptions: {
					isIndeterminate: false,
					isIndeterminateup: false,
					isIndeterminatedown: false,
					checkAll: false,
					checkUp: false,
					checkDown: false,
				},
				loading: false,
				loadingMsg: "",
				disabledTxt: false,
				stepUp: 0, //上行门的step值
				stepDown: 0, //下行门的step值
				stationSide: 0, //选中上下行
			};
		},
		watch: {
			"dataForm.dcu": {
				handler(val) {
					if (val.length === 0) {
						this.dataForm.cpuId = 0;
					}
				},
				deep: true,
				immediate: true,
			},
			jdNumber(val) {
				var arr = this.loadingMsg.split('......')
				this.loadingMsg = arr[0] + '......' + val
			}
		},
		computed: {
			dataRule() {
				return {
					cpuId: [{
						required: true,
						message: "CPU类型不能为空",
						trigger: "blur",
					}, ],
					dcu: [{
						required: true,
						message: "门空单元编号不能为空",
						trigger: "blur",
					}, ],
				};
			},
		},
		mounted() {

		},
		methods: {
			init(path, status) {
				this.visible = true;
				this.dataForm.packagePath = path;
				this.$nextTick(() => {
					this.$refs["dataForm"].resetFields();
					this.getdoorList();
				});
			},
			// 流向全选
			handleCheckAllChange(e) {
				this.dataForm.dcu = e ? this.options2.map((item) => item.dcu) : [];
				this.checkOptions.isIndeterminate = false;
				this.checkOptions.isIndeterminateup = false;
				this.checkOptions.isIndeterminatedown = false;
				this.checkOptions.checkUp = 0;
				this.checkOptions.checkDown = 0;
			},
			handleCheckUpChange(e) {
				this.dataForm.dcu = e ? this.optionsup.map((item) => item.dcu) : [];
				this.checkOptions.isIndeterminate = false;
				this.checkOptions.isIndeterminateup = false;
				this.checkOptions.isIndeterminatedown = false;
				this.checkOptions.checkAll = 0;
				this.checkOptions.checkDown = 0;
			},
			handleCheckDownChange(e) {
				this.dataForm.dcu = e ? this.optionsdown.map((item) => item.dcu) : [];
				this.checkOptions.isIndeterminate = false;
				this.checkOptions.isIndeterminateup = false;
				this.checkOptions.isIndeterminatedown = false;
				this.checkOptions.checkAll = 0;
				this.checkOptions.checkUp = 0;
			},
			getdoorChange(val) {
				const nowLength = this.dataForm.dcu.length;
				this.checkOptions.isIndeterminate =
					nowLength > 0 && nowLength < this.options2.length;
				this.checkOptions.isIndeterminateup =
					nowLength > 0 && nowLength < this.optionsup.length;
				this.checkOptions.isIndeterminatedown =
					nowLength > 0 && nowLength < this.optionsdown.length;
				this.checkOptions.checkAll = nowLength == this.options2.length;
				this.checkOptions.checkUp = nowLength == this.optionsup.length;
				this.checkOptions.checkDown = nowLength == this.optionsdown.length;
				this.$forceUpdate();
			},
			getdoorList() {
				this.$http.get("/psc/door/getDoor").then((res) => {
					this.options2 = res.data.data.up.concat(res.data.data.down);
					this.optionsup = res.data.data.up;
					this.optionsdown = res.data.data.down;
					//获取上下行数据要增加和减少的值-----2023年5月26日
					this.stepUp = getStep(res.data.data.up)
					this.stepDown = getStep(res.data.data.down)
					// console.log( this.stepUp,this.stepDown,'上下行的step的值')
					//获取上下行数据要增加和减少的值-----2023年5月26日
					for (var i = 0; i < this.options2.length; i++) {
						if (
							this.options2[i].doorType === 0 ||
							this.options2[i].doorType === 2
						) {
							this.options2.splice(i, 1); // 将使后面的元素依次前移，数组长度减1
							i--; // 如果不减，将漏掉一个元素
						}
					}
					for (var i = 0; i < this.optionsup.length; i++) {
						if (
							this.optionsup[i].doorType === 0 ||
							this.optionsup[i].doorType === 2
						) {
							this.optionsup.splice(i, 1); // 将使后面的元素依次前移，数组长度减1
							i--; // 如果不减，将漏掉一个元素
						}
					}
					for (var i = 0; i < this.optionsdown.length; i++) {
						if (
							this.optionsdown[i].doorType === 0 ||
							this.optionsdown[i].doorType === 2
						) {
							this.optionsdown.splice(i, 1); // 将使后面的元素依次前移，数组长度减1
							i--; // 如果不减，将漏掉一个元素
						}
					}
				});
			},
			close() {
				this.checkOptions = {
					isIndeterminate: false,
					isIndeterminateup: false,
					isIndeterminatedown: false,
					checkAll: false,
					checkUp: false,
					checkDown: false,
				};
			},
			dataFormSubmitHandle: debounce(
				function() {
					this.$refs["dataForm"].validate((valid) => {
						if (!valid) {
							return false;
						}
						// 清空失败门编号
						this.$emit('clearData', 1)
						var obj = {
							cpuType: this.dataForm.cpuId,
							dcuArr: this.returnDoorId(),
							upgradePackagePath: this.dataForm.packagePath,
						};
						this.loading = true;
						var that = this;
						this.command(obj)
							.then(function(data) {
								if (data == 1) {
									return that.start(obj);
								} else {
									that.loading = false;
									that.visible = false;
									that.disabledTxt = true
									that.$emit('disabledTxt', that.disabledTxt)
								}
							})
							.then(function(data) {
								if (data == 1) {
									return that.restart(obj);
								} else {
									that.loading = false;
									that.visible = false;
									that.disabledTxt = true
									that.$emit('disabledTxt', that.disabledTxt)
								}
							})
							.then(function(data) {
								if (data == 1) {
									that.loading = false;
									that.visible = false;
								} else {
									that.loading = false;
									that.visible = false;
								}
								that.disabledTxt = true
								that.$emit('disabledTxt', that.disabledTxt)
							})
							.catch((err) => {
								that.loading = false;
								that.visible = false;
								that.disabledTxt = true
								that.$emit('disabledTxt', that.disabledTxt)
							});
					});
				},
				1000, {
					leading: true,
					trailing: false,
				}
			),
			//准备命令
			command(data) {
				this.loadingMsg = "进入Bootloader中......";
				var that = this;
				var p = new Promise(function(resolve, reject) {
					//做一些异步操作
					that.$http.post("/psc/dcu/upgradePrepare", data).then((res) => {
						if (res.data.code !== 0) {
							resolve("0");
							return that.$message.error(res.data.msg);
						}
						that.loadingMsg = res.data.data;
						setTimeout(function() {
							resolve("1");
						}, 2000);
					});
				});
				return p;
			},
			// 开始命令
			start(data) {
				this.loadingMsg = "发送bin文件中......";
				var that = this;
				var p = new Promise(function(resolve, reject) {
					      //做一些异步操作
					      axios({
						url:window.SITE_CONFIG['apiURL']+"/psc/dcu/upgradeStart",
						method:'POST',
						data:data,
						headers:{
							'Accept-Language':Cookies.get('language') || 'zh-CN',
							'Authorization':Cookies.get('token')|| '',
							'content-type':'application/json;charset=UTF-8'
						},
						timeout: 1000 * 750,
						withCredentials: true
					}).then((res) => {
					        if (res.data.code !== 0) {
					          resolve("0");
					          return that.$message.error(res.data.msg);
					        }
					        that.loadingMsg = res.data.data;
					        setTimeout(function () {
					          resolve("1");
					        }, 2000);
					});
					// //做一些异步操作
					// that.$http.post("/psc/dcu/upgradeStart", data).then((res) => {
					// 	if (res.data.code !== 0) {
					// 		resolve("0");
					// 		return that.$message.error(res.data.msg);
					// 	}
					// 	that.loadingMsg = res.data.data;
					// 	setTimeout(function() {
					// 		resolve("1");
					// 	}, 2000);
					// });
				});
				return p;
			},
			//重启命令
			restart(data) {
				this.loadingMsg = "重启DCU......";
				var that = this;
				var p = new Promise(function(resolve, reject) {
					//做一些异步操作
					that.$http.get("/psc/dcu/upgradeRestart").then((res) => {
						if (res.data.code !== 0) {
							resolve("0");
							return that.$message.error(res.data.msg);
						}
						that.loadingMsg = res.data.data;
						setTimeout(function() {
							resolve("1");
						}, 2000);
					});
				});
				return p;
			},
			returnDoorId() {
				var doorNum = [];
				for (var i = 0; i < this.dataForm.dcu.length; i++) {
					for (var j = 0; j < this.options2.length; j++) {
						if (Number(this.dataForm.dcu[i]) == this.options2[j].dcu && this.options2[j].stationSide == 1) {
							let num1 = Number(this.dataForm.dcu[i]) - this.stepUp;
							doorNum.push(num1);
						} else if (Number(this.dataForm.dcu[i]) == this.options2[j].dcu && this.options2[j].stationSide ==
							0) {
							let num1 = Number(this.dataForm.dcu[i]) - this.stepDown + 128;
							doorNum.push(num1);
						}
					}
				}
				return doorNum;
			},
			//关闭弹窗
			closeLoading() {
				this.loading = false
				var that = this
				//去掉升级
				this.$http.get("/psc/dcu/upgradeStop").then((res) => {
					if (res.data.code !== 0) {
						return that.$message.error(res.data.msg);
					}
					this.$message({
						message: res.data.msg,
						type: "success",
						duration: 3000,
					});
					that.disabledTxt = true
					that.$emit('disabledTxt', that.disabledTxt)
				})
			}
		},
	};
</script>
<style scoped>
	.loadingContent {
		width: 100vw;
		height: 100vh;
		position: fixed;
		top: 0;
		left: 0;
		z-index: 9999999999;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.loadingClose {
		position: absolute;
		width: 20px;
		height: 20px;
		cursor: pointer;
		top: 20px;
		right: 20px;
	}

	.loadingClose:before {
		position: absolute;
		content: "";
		width: 2px;
		height: 25px;
		background: #fff;
		transform: rotate(45deg);
		top: -3px;
		left: 11px;
	}

	.loadingClose:after {
		content: "";
		position: absolute;
		width: 2px;
		height: 25px;
		background: #fff;
		transform: rotate(-45deg);
		top: -3px;
		left: 11px;
	}
</style>
